import crypto from './crypto.js'
import Vue from 'vue'
import { isArray } from '@/libs/tools.js'
let controlBtn = true // 权限功能关闭
function bindPermisson(obj) {
    /** 权限指令,对按钮权限的控制 **/
    obj.directive('permission', {
        inserted: function(el, binding) {
            let { action, isExist } = obj.prototype.$_has(binding.value)
            if (!isExist) {
                switch (action) {
                    case '0':
                        if (el.parentNode) {
                            el.parentNode.removeChild(el)
                        }
                        break
                    case '1':
                        el.setAttribute('disabled', true)
                        el.style.background = 'rgba(240,240,240,.4)'
                        el.style.color = '#2D3040'
                        el.style.border = '1px solid #E0E0E0'
                        break
                }
            }
        },
        update: function(el, binding) {
            let { action, isExist } = obj.prototype.$_has(binding.value)
            if (!isExist) {
                switch (action) {
                    case '0':
                        if (el.parentNode) {
                            el.parentNode.removeChild(el)
                        }
                        break
                    case '1':
                        el.setAttribute('disabled', true)
                        el.style.background = 'rgba(240,240,240,.4)'
                        el.style.color = '#2D3040'
                        el.style.border = '1px solid #E0E0E0'
                        break
                }
            }
        }
    })
    // 权限检查方法（且把该方法添加到vue原型中）
    obj.prototype.$_has = function(value) {
        let isExist = false
        if (controlBtn) {
            let randomFlag = localStorage.getItem('randomFlag')
            if (randomFlag) {
                let permissionData = JSON.parse(crypto.decrypt(localStorage.getItem(randomFlag)))
                var permissionList = permissionData.permission.length > 0 ? permissionData.permission : []
                var permissionAction = permissionData.noAccessType ? permissionData.noAccessType : ''
            } else {
                permissionList = []
                permissionAction = '0'
            }
            if (permissionList === undefined || permissionList == null) {
                return false
            }
            if (isArray(value)) {
                value.forEach((item) => {
                    if (permissionList.indexOf(item) >= 0) {
                        isExist = true
                    }
                })
            } else {
                if (permissionList.indexOf(value) >= 0) {
                    // 若在按钮中定义的权限字段能在后端返回的权限数组中能找到，则该按钮可显示
                    isExist = true
                }
            }
        }
        let obj = {
            isExist: isExist,
            action: permissionAction || ''
        }
        return obj
    }
}
bindPermisson(Vue)
